package sy.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import sy.model.SysProject;


/**
 * 用于模拟HTTP请求中GET/POST方式 
 * @author landa
 *
 */
public class HttpUtils {  
	/** 
	 * 发送GET请求 
	 *  
	 * @param url 
	 *            目的地址 
	 * @param parameters 
	 *            请求参数，Map类型。 
	 * @return 远程响应结果 
	 */  
	public static String sendGet(String url, Map<String, String> parameters) { 
		String result="";
		BufferedReader in = null;// 读取响应输入流  
		StringBuffer sb = new StringBuffer();// 存储参数  
		String params = "";// 编码之后的参数
		try {
			// 编码请求参数  
			if(parameters.size()==1){
				for(String name:parameters.keySet()){
					sb.append(name).append("=").append(
							java.net.URLEncoder.encode(parameters.get(name),  
									"UTF-8"));
				}
				params=sb.toString();
			}else{
				for (String name : parameters.keySet()) {  
					sb.append(name).append("=").append(  
							java.net.URLEncoder.encode(parameters.get(name),  
									"UTF-8")).append("&");  
				}  
				String temp_params = sb.toString();  
				params = temp_params.substring(0, temp_params.length() - 1);  
			}
			String full_url = url + "?" + params; 
			System.out.println(full_url); 
			// 创建URL对象  
			java.net.URL connURL = new java.net.URL(full_url);  
			// 打开URL连接  
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
					.openConnection();  
			// 设置通用属性  
			httpConn.setRequestProperty("Accept", "*/*");  
			httpConn.setRequestProperty("Connection", "Keep-Alive");  
			httpConn.setRequestProperty("User-Agent",  
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
			// 建立实际的连接  
			httpConn.connect();  
			// 响应头部获取  
			Map<String, List<String>> headers = httpConn.getHeaderFields();  
			// 遍历所有的响应头字段  
			for (String key : headers.keySet()) {  
				System.out.println(key + "\t：\t" + headers.get(key));  
			}  
			// 定义BufferedReader输入流来读取URL的响应,并设置编码方式  
			in = new BufferedReader(new InputStreamReader(httpConn  
					.getInputStream(), "UTF-8"));  
			String line;  
			// 读取返回的内容  
			while ((line = in.readLine()) != null) {  
				result += line;  
			}  
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {  
				if (in != null) {  
					in.close();  
				}  
			} catch (IOException ex) {  
				ex.printStackTrace();  
			}  
		}
		return result ;
	}  

	/** 
	 * 发送POST请求 
	 *  
	 * @param url 
	 *            目的地址 
	 * @param parameters 
	 *            请求参数，Map类型。 
	 * @return 远程响应结果 
	 */  
	public static String sendPost(String url, Map<String, String> parameters) {  
		String result = "";// 返回的结果  
		BufferedReader in = null;// 读取响应输入流  
		PrintWriter out = null;  
		StringBuffer sb = new StringBuffer();// 处理请求参数  
		String params = "";// 编码之后的参数  
		try {  
			// 编码请求参数  
			if (parameters.size() == 1) {  
				for (String name : parameters.keySet()) {  
					sb.append(name).append("=").append(  
							java.net.URLEncoder.encode(parameters.get(name),  
									"UTF-8"));  
				}  
				params = sb.toString();  
			} else {  
				for (String name : parameters.keySet()) {  
					sb.append(name).append("=").append(  
							java.net.URLEncoder.encode(parameters.get(name),  
									"UTF-8")).append("&");  
				}  
				String temp_params = sb.toString();  
				params = temp_params.substring(0, temp_params.length() - 1);  
			}  
			// 创建URL对象  
			java.net.URL connURL = new java.net.URL(url);  
			// 打开URL连接  
			java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL  
					.openConnection();  
			// 设置通用属性  
			httpConn.setRequestProperty("Accept", "*/*");  
			httpConn.setRequestProperty("Connection", "Keep-Alive");  
			httpConn.setRequestProperty("User-Agent",  
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");  
			// 设置POST方式  
			httpConn.setDoInput(true);  
			httpConn.setDoOutput(true);  
			// 获取HttpURLConnection对象对应的输出流  
			out = new PrintWriter(httpConn.getOutputStream());  
			// 发送请求参数  
			out.write(params);  
			// flush输出流的缓冲  
			out.flush();  
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式  
			in = new BufferedReader(new InputStreamReader(httpConn  
					.getInputStream(), "UTF-8"));  
			String line;  
			// 读取返回的内容  
			while ((line = in.readLine()) != null) {  
				result += line;  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			try {  
				if (out != null) {  
					out.close();  
				}  
				if (in != null) {  
					in.close();  
				}  
			} catch (IOException ex) {  
				ex.printStackTrace();  
			}  
		}  
		return result;  
	} 
	

	/**
	 * 
	 * @Title: sendGetRest
	 * @Description: 绕过ssl认证，直接调用第三方api的restful接口
	 * @param: @param urlStr
	 * @param: @param requestMethod
	 * @param: @return
	 * @param: @throws IOException
	 * @param: @throws KeyManagementException
	 * @param: @throws NoSuchAlgorithmException     
	 * @return: String     
	 * @author:  xieyuanqiu
	 * @date: 2017年9月5日 上午10:35:32
	 * @throws
	 */
	public static String sendGetRest(String urlStr, String requestMethod) throws IOException, KeyManagementException, NoSuchAlgorithmException{
		String result = "";
		HttpsURLConnection.setDefaultHostnameVerifier(new HttpUtils().new NullHostNameVerifier());
		SSLContext sc = SSLContext.getInstance("TLS");
		sc.init(null, trustAllCerts, new SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		URL url = new URL(urlStr);
		// 打开restful链接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(requestMethod);// POST GET PUT DELETE
		// 设置访问提交模式，表单提交
		conn.setRequestProperty("User-Agent",  
				"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); 
		conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
		conn.setConnectTimeout(130000);// 连接超时 单位毫秒
		conn.setReadTimeout(130000);// 读取超时 单位毫秒
		// 读取请求返回值
		int httpResponseCode = conn.getResponseCode();
		if(conn.getResponseCode()==200){
			BufferedReader in = null;// 读取响应输入流  
			in = new BufferedReader(new InputStreamReader(conn  
					.getInputStream(), "UTF-8"));  
			String line;  
			// 读取返回的内容  
			while ((line = in.readLine()) != null) {  
				result += line;  
			} 
		}else{
			JSONObject obj = new JSONObject();
			obj.put("httpResponseCode", httpResponseCode);
			result = obj.toJSONString();
		}
		return result;
	}
	static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}
		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}
	} };
	public class NullHostNameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String arg0, SSLSession arg1) {
			// TODO Auto-generated method stub
			return true;
		}
	}
	/********************以上为远程调用第三方api的restful接口相关代码，绕过了ssl认证***********************/




	/** 
	 * 主函数，测试请求 
	 *  
	 * @param args 
	 */  
	public static void main(String[] args) {  
		String result = "";
		/**
		 * 门禁授权接口
		 * link:http://202.105.104.101:9001/authenticate
		 * 请求方式：post
		 * 输入参数：
		 * reqId: 请求代码【不为空，随意填】
		 * upid: 项目唯一编号unique project identifier【现在的门禁服务器上设置的一个项目编号为 1234】
		 * bldgId: unique building identifier 【暂时传1】
		 * unitId: 单元编号 【暂时传2】
		 * personId: 人员编号 【可为空】
		 * personType: 人员类型 【传 YZ】
		 * phone: 手机号码【可为空】
		 * name: 人员姓名 【可为空】
		 */
		/*        Map<String, String> parametersAuthenticate = new HashMap<String, String>();  
        parametersAuthenticate.put("reqId", "testId");  
        parametersAuthenticate.put("upid", "1234");
        parametersAuthenticate.put("bldgId", "1");
        parametersAuthenticate.put("unitId", "2");  
        parametersAuthenticate.put("personId", "");
        parametersAuthenticate.put("personType", "YZ");
        parametersAuthenticate.put("phone", "");  
        parametersAuthenticate.put("name", "");
        String resultAuthenticate =sendPost("http://112.74.19.135:1111/ssh/v1/appBusiness/iot/entrance/authenticate", parametersAuthenticate);
        System.out.println(resultAuthenticate); */


		/**
		 * 门禁开门接口
		 * link:http://202.105.104.101:9001/openDoor
		 * 请求方式：post
		 * 输入参数：
		 * reqId:请求代码 【不为空，随意填】
		 * upid:项目唯一编号unique project identifier【现在的门禁服务器上设置的一个项目编号为 1234】
		 * doorId：门ID 【在鉴权中获得的MID】
		 * phone:手机号码 【可为空】
		 * personId:人员编号【可为空】
		 * name:人员姓名 【可为空】
		 */
		/*        Map<String, String> parametersOpenDoor = new HashMap<String, String>();  
        parametersOpenDoor.put("reqId", "testId");  
        parametersOpenDoor.put("upid", "1234");
        parametersOpenDoor.put("doorId", "319");
        parametersOpenDoor.put("phone", ""); 
        parametersOpenDoor.put("personId", "");
        parametersOpenDoor.put("name", "");
        String resultOpenDoor =sendPost("http://202.105.104.101:9001/openDoor", parametersOpenDoor);
        System.out.println(resultOpenDoor); */


		/*    	String result;
		try {
			result = sendGetRest("http://202.105.104.101:9001/test/getDoorId", "GET");
			JSONObject objectResult1 = JSONObject.parseObject(result);
			String JQResult =(String)objectResult1.get("JQResult");
			JSONObject objectResult2 =JSONObject.parseObject(JQResult);

		    String st2 = (String)objectResult2.get("XX");
			System.out.println(objectResult1);
		    JSONArray jsonArray  = objectResult2.getJSONArray("MLB");
		    int iSize = jsonArray.size();
		    for (int i = 0; i < iSize; i++) {
		    	JSONObject jsonObj = jsonArray.getJSONObject(i);
		    	System.out.println("MID:" + jsonObj.get("MID"));
		    	System.out.println("MMC:" + jsonObj.get("MMC"));
		    }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} */

		/**
		 * 机房远程监控 -返回有权限的所有项目
		 * link:http://202.105.104.105:8804/project/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1
		 * 请求方式：get
		 */
		/*    	String result;
			try {
				result = sendGetRest("http://localhost:8080/ssh/v1/appBusiness/iot/machine/project", "GET");

				JSONObject objectResult1 = JSONObject.parseObject(result);
				int state = (int)objectResult1.get("state");
				String me = (String)objectResult1.get("errorMessage");
			    JSONArray jsonArray = JSONArray.parseArray(objectResult1.getString("data"));				
				int iSize = jsonArray.size();
			    for (int i = 0; i < iSize; i++) {
			    	JSONObject jsonObj = jsonArray.getJSONObject(i);
			    	//System.out.println(jsonObj);
		    }

				System.out.println(result);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/

		/**
		 * 机房远程监控 -返回有权限的所有项目
		 * link:http://202.105.104.105:8804/device/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1
		 * 请求方式：post
		 */


		/**
		 * 机房远程监控测试---返回有权限的所有项目
		 * 返回项目信息包含在key=data中，返回项目字段：projectCode，projectName，ccProjectCode
		 * token:bd4f1ce1b544463094726ebc23a6c9f1
		 * 请求方式：GET
		 */
		/*		try {
			result = sendGetRest("http://202.105.104.105:8804/project/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1", "GET");
			JSONObject obj = JSONObject.parseObject(result);
			JSONArray arry = obj.getJSONArray("data");
			List<SysProject> list = new ArrayList<SysProject>();
			for(int i = 0;i<arry.size(); i++){
				JSONObject obj1 = (JSONObject) JSONArray.parse(arry.getString(i));
				SysProject pro = new SysProject();
				pro.setCode(obj.getString("projectCode"));
				pro.setName(obj1.getString("projectName"));
				list.add(pro);
			}
			System.out.println(list.get(0).getName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} */


		/**
		 * 机房远程监控测试---获取项目下所有参数信息
		 * token:bd4f1ce1b544463094726ebc23a6c9f1
		 * http请求方式: POST
		 * 请求参数：ProjectCode
		 * 请求示例：http://webapi.eegrid.com/deviceparame/get?AccessToken=ACCESSTOKEN
		 */
		/*    	 Map<String, String> params = new HashMap<String, String>();
    	
    	
    	/**
    	 * 机房远程监控测试---获取项目下所有参数信息
    	 * token:bd4f1ce1b544463094726ebc23a6c9f1
    	 * http请求方式: POST
    	 * 请求参数：ProjectCode
    	 * 请求示例：http://webapi.eegrid.com/deviceparame/get?AccessToken=ACCESSTOKEN
    	 */
    	 Map<String, String> params = new HashMap<String, String>();
    	 params.put("ProjectCode", "201");//中海华庭
    	 result = sendPost("http://202.105.104.105:8804/deviceparame/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1", params);
    	 System.out.println(result);

		/**
		 * 机房远程监控测试---返回项目下所有设备信息
		 * token:bd4f1ce1b544463094726ebc23a6c9f1
		 * http请求方式: POST
		 * 请求参数：ProjectCode
		 * 请求示例：http://webapi.eegrid.com/device/get?AccessToken=ACCESSTOKEN
		 */
		/*    	 Map<String, String> params = new HashMap<String, String>();
    	 params.put("token", "f53718b2-bc88-4082-a749-b7da562cda75");//中海华庭
    	 result = sendPost("http://localhost:8080/ssh/v1/wyBusiness/iot/machine/device", params);
    	 System.out.println(result);
    	
    	/**
    	 * 机房远程监控测试---返回项目下所有设备信息
    	 * token:bd4f1ce1b544463094726ebc23a6c9f1
    	 * http请求方式: POST
    	 * 请求参数：ProjectCode
    	 * 请求示例：http://webapi.eegrid.com/device/get?AccessToken=ACCESSTOKEN
    	 */
/*    	 Map<String, String> params = new HashMap<String, String>();
    	 params.put("ProjectCode", "201");//中海华庭
    	 result = sendPost("http://202.105.104.105:8804/device/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1", params);
    	 System.out.println(result);*/

		/**
		 * 机房远程监控测试---某项目所有设备当前实时数据
		 * token:bd4f1ce1b544463094726ebc23a6c9f1
		 * http请求方式: POST
		 * 请求参数：ProjectCode
		 * 请求示例：http://webapi.eegrid.com/realdata/get?AccessToken=ACCESSTOKEN
		 */
		/*    	 Map<String, String> params = new HashMap<String, String>();
    	 params.put("ProjectCode", "201");//中海华庭
    	 result = sendPost("http://202.105.104.105:8804/realdata/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1", params);
    	 System.out.println(result);*/
		/*	        Map<String, String> parameters = new HashMap<String, String>();  
	        parameters.put("ProjectCode", "201");  
			String result =sendPost("http://202.105.104.105:8804/device/get?AccessToken=bd4f1ce1b544463094726ebc23a6c9f1", parameters);
			System.out.println(result); */

		/**
		 * 巡更api接口测试----获取token
		 * api地址:https://192.168.200.111:8443/zhwy/rest/v1/admin/system/request_token
		 * token = 2dae3e2b447f493892b5bb90b79b68bb
		 */
		/*    		String result;
    		try {
				result = sendGetRest("https://192.168.200.111:8443/zhwy/rest/v1/admin/system/request_token", "GET");
				JSONObject jsonObject =JSONObject.parseObject(result);
				System.out.println(jsonObject);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */

		/**
		 * 巡更api接口测试----获取token
		 * api地址:https://192.168.200.111:8443/zhwy/rest/v1/areas?token=2dae3e2b447f493892b5bb90b79b68bb
		 */
		/*    		try {
    		
	    	/**
	    	 * 巡更api接口测试----获取token
	    	 * api地址:https://192.168.200.111:8443/zhwy/rest/v1/areas?token=2dae3e2b447f493892b5bb90b79b68bb
	    	 */
/*    		try {
				result = sendGetRest("https://192.168.200.111:8443/zhwy/rest/v1/areas?token=2dae3e2b447f493892b5bb90b79b68bb", "GET");
				//JSONArray jsonOArray = JSONArray.parseArray(result);
				System.out.println(result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */
/*		try {
			result = sendGetRest("http://202.105.104.105:8003/park_car_out_exceptions","GET");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("result="+"null".equals(result));*/
	}  
}
